package com.b2.controller.wx;

import com.aliyuncs.auth.sts.AssumeRoleResponse;
import com.b2.pojo.entity.AliOss;
import com.b2.result.Result;
import com.b2.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.security.SecureRandom;

@RestController
@Api(tags = "通用接口")
@RequestMapping("/wx/common")
@Slf4j
@CrossOrigin
public class WxCommonController {

    @Resource
    private AliOssUtil aliOssUtil;

    @PostMapping("/upload")
    @ApiOperation("上传视频文件")
    public Result<String> upload(@ApiParam("视频")@RequestParam("file") MultipartFile file) {
        String fileUrl = null;
        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        String finalFileName = "wx/video/" + System.currentTimeMillis() + "" + new SecureRandom().nextInt(0x0400) + suffixName;
        try {
            fileUrl = aliOssUtil.upload(file.getBytes(), finalFileName);
        } catch (IOException e) {
            log.info("文件上传失败",e);
        }
        return Result.success(fileUrl);
    }

    @GetMapping("/access")
    @ApiOperation("获取临时凭证")
    public Result<AliOss> access() {
        AssumeRoleResponse response = aliOssUtil.getRAM();
        AliOss aliOss = new AliOss();
        aliOss.setAccessKeyId(response.getCredentials().getAccessKeyId());
        aliOss.setAccessKeySecret(response.getCredentials().getAccessKeySecret());
            aliOss.setSecurityToken(response.getCredentials().getSecurityToken());
            return Result.success(aliOss);
        }

}
